package org.csu.web.servlets;

import org.csu.domain.Account;
import org.csu.domain.Cart;
import org.csu.domain.Item;
import org.csu.service.CartService;
import org.csu.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class DeleteItemServlet extends HttpServlet {
    private static final String ERROR_MESSAGE="/WEB-INF/jsp/common/Error.jsp";
    private static final String VIEW_CART="/WEB-INF/jsp/cart/Cart.jsp";
    private String workingItemId;
    private Cart cart;
    private String username;
    private BigDecimal subtoatl;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        workingItemId=req.getParameter("itemid");
        HttpSession session = req.getSession();
        cart = (Cart)session.getAttribute("cart");
        username = req.getParameter("username");

            if(username != null){
                HttpServletRequest httpRequest= req;
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());
                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") + strBackUrl + " " + workingItemId + " 已从购物车中移除";
                logService.insertLogInfo(username, logInfo);
            CartService cartService = new CartService();
            cartService.Delete_By_Username_and_Itemid(username,workingItemId);
                List<Cart> cartList = new ArrayList<>();
                if(username!=null)
                cartList = cartService.getCartByusername(username);
                int cartListsize = cartList.size();
                subtoatl=new BigDecimal(0);
                int k=0;
                while (k<cartList.size()){
                    subtoatl=subtoatl.add(cartList.get(k).getTotal());
                    k++;
                }
                session.setAttribute("subTotal",subtoatl);
                session.setAttribute("cartList",cartList);
                session.setAttribute("cartListsize",cartListsize);
            req.getRequestDispatcher(VIEW_CART).forward(req,resp);
        }
    }
}
